package com.universityJob.modules.data.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;


import com.universityJob.common.utils.ExportExcel;
import com.universityJob.common.utils.FileUtil;
import com.universityJob.common.utils.PageUtils;
import com.universityJob.common.utils.R;
import com.universityJob.common.validator.ValidatorUtils;
import com.universityJob.modules.data.entity.DataJobEntity;
import com.universityJob.modules.data.service.DataJobService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
*@ClassName: DataJobController
*@Description
*@Author maozhi
*@Date 2021/3/26
*@Time 13:19
*/
@RestController
@RequestMapping("data/job")
public class DataJobController {
    @Autowired
    private DataJobService jobService;
    /**
     * 存储请求产生的文件名
     */
    Map<String, String> fileInfo = new HashMap<>();
    @Value("${upload.file}excel/")
    String excelPath;
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:job:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = jobService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{jobid}")
    @RequiresPermissions("sys:job:info")
    public R info(@PathVariable("jobid") String jobid){
        DataJobEntity job = jobService.getById(jobid);

        return R.ok().put("job", job);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:job:save")
    public R save(@RequestBody DataJobEntity job){
        job.setPublishdate(new Date());
        jobService.save(job);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:job:update")
    public R update(@RequestBody DataJobEntity job){
        ValidatorUtils.validateEntity(job);
        jobService.updateById(job);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:job:delete")
    public R delete(@RequestBody String[] jobids){
        jobService.removeByIds(Arrays.asList(jobids));

        return R.ok();
    }
    /**
     * 导入数据
     */
    @PostMapping("/inputExcel")
    @RequiresPermissions("sys:job:save")
    public R inputExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        this.fileInfo.put(uid, "-1");
        data.put("uid", uid);
        data.put("fileName","");
        params.put("uid", uid);
        logger.info("开始导入数据");
        Thread thread = new Thread(() -> {
            try {
                int i = jobService.inputExcel(response, params);
                this.fileInfo.put(uid, String.valueOf(i));
                logger.info("数据导入成功！");
            } catch (Exception e) {
                logger.error("数据导入出错！");
            }
        });
        thread.start();

        return R.ok(data);
    }
    /**
     * 导出excel
     */
    @PostMapping("/exportExcel")
    @RequiresPermissions("sys:job:save")
    public R exportExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        this.fileInfo.put(uid, "0");
        data.put("uid", uid);
        data.put("fileName", params.get("fileName"));
        params.put("path", excelPath);
        params.put("uid", uid);
        logger.info("开始准备Excel文件：{}",params.get("fileName"));
        Thread thread = new Thread(() -> {
            try {
                int i = jobService.exportStatisticsReport(response, params);
                this.fileInfo.put(uid, String.valueOf(i));
                logger.info("文件已经准备好，准备开始下载！");
            } catch (Exception e) {
                logger.error("文件导出出错！");
            }
        });
        thread.start();

        return R.ok(data);
    }
    /**
     * 循环请求接口
     */
    @PostMapping("/testpolling")
    @ResponseBody
    public R testPolling(@RequestBody Map<String, Object> param) {
        String uid = ExportExcel.nvll(param.get("uid"));
        String fileName = ExportExcel.nvll(param.get("fileName"));
        Map<String, Object> pollingData = new HashMap<>();
        pollingData.put(uid, fileInfo.get(uid));
        pollingData.put("fileName", fileName);
        return R.ok(pollingData);
    }
    /**
     * 最后下载的接口
     */
    @RequestMapping("/testdownload")
    @ResponseBody
    public void testDownload(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        String fileName = (String) param.get("fileName");
        String uid = ExportExcel.nvll(param.get("uid"));
        String uidFolder = excelPath + uid;
        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(uidFolder + "/" + fileName)));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data;charset=utf-8");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            byte[] buf = new byte[2048];
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            out.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除临时文件和文件信息
            FileUtil.deleteDirectory(uidFolder);
            fileInfo.remove(uid);
        }
    }
}
